package com.gingko.duominuo.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.observe
import com.gingko.duominuo.ui.activity.BaseActivity
import com.gingko.duominuo.utils.logi
import com.gingko.duominuo.viewmodel.BaseViewModel

abstract class BaseFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return getContentView(inflater,container)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getViewModel()?.loadingLiveData?.observe(owner = viewLifecycleOwner) {
            "fragment--isShowLoading:$it".logi("------------>")
            if (it) {
                showLoading()
            } else {
                dismissLoading()
            }
        }
        initView(view, savedInstanceState)
    }

    abstract fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View?

    abstract fun getViewModel(): BaseViewModel?

    abstract fun initView(view: View, savedInstanceState: Bundle?)


    fun showLoading() {
        if (activity is BaseActivity) {
            (activity as BaseActivity).showLoading()
        }
    }

    fun dismissLoading() {
        if (activity is BaseActivity) {
            (activity as BaseActivity).dismissLoading()
        }
    }

    companion object {
        private const val STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"
    }
}